/**
 * @Title: WeinxinLogin
 * @Package cn.com.yiqi.wsc.api.controller
 * @Description: TODO
 * Copyright: Copyright (c) 2016
 * Company: 成都壹柒互动科技有限公司
 * @author 会员系统组-林威
 * @date 2017/2/17 11:40
 * @version V1.0
 */
package cn.com.yiqi.wsc.api.controller;

import cn.com.yiqi.wsc.Ro.CustomerRo;

import cn.com.yiqi.wsc.api.controller.ro.WxUrlRO;
import cn.com.yiqi.wsc.common.Result;
import cn.com.yiqi.wsc.common.ResultUtil;
import cn.com.yiqi.wsc.ro.WeixinInfoRO;
import cn.com.yiqi.wsc.service.base.BaseParaService;
import cn.com.yiqi.wsc.service.customer.CustomerService;
import cn.com.yiqi.wsc.service.weixin.impl.WeixinPayImpl;
import cn.com.yiqi.wsc.service.weixin.wxDo.WxSignDO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author 会员系统组-林威
 * @ClassName: WeinxinLogin
 * Description: TODO
 * @date 2017/2/17 11:40
 */

@Controller
@RequestMapping("/api/wxAuth")
public class WeinxinLogin {

    @Autowired
    WeixinPayImpl weixinPay;

    @Autowired
    CustomerService customerService;

    @Autowired
    BaseParaService baseParaService;

    /**
     * 微信回调接口
     */
    @RequestMapping(value = "/callback", method = RequestMethod.GET)
    public String callback(HttpServletRequest request) {
        String code = request.getParameter("code");
        String state = request.getParameter("state");
        if(StringUtils.isEmpty(state)){
            state = "t1";
        }
        Map<String, String> urlMap = WxUrlRO.getMap();
        Map<String, Object> map = weixinPay.access_token(code);
        //判断用户已被删除
        String openId = map == null ? null : map.get("openid").toString();
        if (customerService.isDelete(openId)){
            //mv.addObject("msg", "用户已被删除或禁用！");
            return "redirect:/api/wxAuth/error?msg=用户已被删除或禁用";
        }
        //获取access_token
        String access_token = baseParaService.getAccesstoken();
        WeixinInfoRO weixinInfoRO = weixinPay.getwxUserInfoAttention(access_token, map.get("openid").toString());
        weixinInfoRO.setToken(map.get("access_token").toString());
        weixinInfoRO.setRefreshToken(map.get("refresh_token").toString());
        //token失效
        if (weixinInfoRO.getErrcode() != null) {
            // 返回失败提示
            return  "redirect:/api/wxAuth/error?msg=未知错误";
        }
        //未关注
        if (weixinInfoRO.getSubscribe() == 0) {
            weixinInfoRO = weixinPay.getwxUserInfo(map.get("access_token").toString(), map.get("openid").toString());
            weixinInfoRO.setSubscribe(0);
        }
        String []type = state.split(",");
        String urlKey = type[0];
        Integer pid = 0;
        String id =null;

        if(type[0].equals("t3") || type[0].equals("t7") || type[0].equals("t71") || type[0].equals("t72") || type[0].equals("t8") || type[0].equals("t9")){
        	
        	//分享页面ID
        	id =  type[1];
        	 
            try{
            	//分享人
                pid = Integer.parseInt(type[2]);
            }catch (Exception e){
            	pid = 0;
            }
        }else{
        	 try{
        		//分享人
        		pid = Integer.parseInt(type[1]);
        	 }catch (Exception e){
             	pid = 0;
             }
        }
        
        // 分销关系未关注返回t6
        if(pid != 0 && weixinInfoRO.getSubscribe() == 0){
            urlKey = "t6";
        }
        
        CustomerRo customer = customerService.updateOrInsertUser(weixinInfoRO, pid);

        String siteName = urlMap.get(urlKey);//获取对应页面地址

        if(urlKey.equals("t6")){//邀请页
        	if(pid == 0){//分享人ID不存在
        		siteName = urlMap.get("t1");
        	}else{
        		siteName +="uid="+ pid+"&";
        	}
        }else if(StringUtils.isNotEmpty(id)){
        	if(urlKey.equals("t7")){//商品/服务列表 没有Id  只有商品与服务分类
        		siteName +="type="+ id+"&";
        	}else{
        		 siteName +="id="+ id+"&";
        	}
        }
        //当前登录人ID
        siteName +="userId="+customer.getId();
        System.out.println("跳转地址:"+siteName);
        return siteName;
    }

    /**
     * 入口
     **/
    @RequestMapping("/index")
    public String index(HttpServletRequest request) {
        //重定向参数
        String typeStr = request.getParameter("type");
        String state = "";
        String uid = request.getParameter("uid");
        String id = request.getParameter("id");
        switch (typeStr)
        {
            case "t1":
                state = typeStr+","+uid;
                break;
            case "t2":
                state = typeStr+","+uid;
                break;
            case "t3":
                state = typeStr+","+id+","+uid;
                break;
            case "t4":
                state = typeStr+","+uid;
                break;
            case "t5":
                state = typeStr+","+uid;
                break;
            case "t51":
                state = typeStr+","+uid;
                break;
            case "t6":
                state = typeStr+","+uid;
                break;
            case "t7":
                state = typeStr+","+id+","+uid;  //id：是商品/服务的区分
                break;
            case "t71":
                state = typeStr+","+id+","+uid;
                break;
            case "t72":
                state = typeStr+","+id+","+uid;
                break;
            case "t8":
                state = typeStr+","+id+","+uid;
                break;
            case "t9":
                state = typeStr+","+id+","+uid;
                break;
            case "t10":
                state = typeStr+","+uid;
                break;
        }
        String url = weixinPay.authUrl(state);
        //return  "redirect:/static/index.html#/content/shoppingMall/ShoppingMall?userId=1";
        return "redirect:" + url;
    }


    @ResponseBody
    @RequestMapping("/jsauth")
    public Result jsAuth(HttpServletRequest request) {
        Result result = new Result();
        String url = request.getParameter("url");
        String tikect = baseParaService.getTicket();
        WxSignDO sign = weixinPay.getSignature(url, tikect);
        ResultUtil.success(result);
        result.putData("sign", sign);
        return result;
    }

    @ResponseBody
    @RequestMapping("/error")
    public Result error(HttpServletRequest request, HttpServletResponse response) {
        String msg="";
        try {
            msg = new String(request.getParameter("msg").getBytes("iso-8859-1"),"utf-8");
        }catch (Exception e){

        }
        response.setCharacterEncoding("utf-8");
        return ResultUtil.fail(new Result(),msg);
    }
    
    
    @RequestMapping(value = "/go/{url}", method = RequestMethod.GET)
    public String callback(@PathVariable("url") String url) {
    	String go = url;
    	if(go.indexOf("+") > 0){
    		go = go.replaceAll("\\+", "/");
    	}

    	if(go.indexOf("_") > 0){
    		go = go.replaceAll("_","?");
    	}
    	return "redirect:/static/index.html#/"+go;
    }

}
